package cn.lzy.web.functionextensionmvc;

import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;

@Component  //注入
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 用户请求 /admin 开头路径时，判断用户是否登录
        String uri = request.getRequestURI();    // http://localhost:8080/myadmin

        Object loginUser = request.getSession().getAttribute("loginUser"); //用户信息
        if (uri.startsWith("/myadmin") && null == loginUser) {
            // 1、uri 是不是以 /myadmin 开头的，并且loginUser 用户信息是空的

            response.sendRedirect("/toLoginPage");
            // 2、http://localhost:8080/myadmin 替换 http://localhost:8080/toLoginPage - login.html文件
            return false;
        }
        return true;}

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        // model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
        // 给 login 登录界面的时间赋值
        request.setAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse
            response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
